package com.goldsprite.gesturerecognizer.core;

import java.util.ArrayList;
import java.util.List;

public class Gesture {
	private List<GesturePoint> points;
	private String name;

	public Gesture(String name) {
		this.name = name;
		this.points = new ArrayList<>();
	}

	public Gesture(String name, List<GesturePoint> points) {
		this.name = name;
		this.points = new ArrayList<>(points);
	}

	public void addPoint(GesturePoint point) {
		points.add(point);
	}

	public List<GesturePoint> getPoints() {
		return points;
	}

	public String getName() {
		return name;
	}

	public int getPointCount() {
		return points.size();
	}

	public GesturePoint getPoint(int index) {
		if (index >= 0 && index < points.size()) {
			return points.get(index);
		}
		return null;
	}

	public Gesture normalize() {
		if (points.size() < 2) return this;

		// 计算边界框
		float minX = Float.MAX_VALUE, minY = Float.MAX_VALUE;
		float maxX = Float.MIN_VALUE, maxY = Float.MIN_VALUE;

		for (GesturePoint point : points) {
			minX = Math.min(minX, point.x);
			minY = Math.min(minY, point.y);
			maxX = Math.max(maxX, point.x);
			maxY = Math.max(maxY, point.y);
		}

		// 归一化到0-1范围
		float width = maxX - minX;
		float height = maxY - minY;
		float scale = Math.max(width, height);

		if (scale == 0) return this;

		List<GesturePoint> normalizedPoints = new ArrayList<>();
		for (GesturePoint point : points) {
			float normalizedX = (point.x - minX) / scale;
			float normalizedY = (point.y - minY) / scale;
			normalizedPoints.add(new GesturePoint(normalizedX, normalizedY));
		}

		return new Gesture(name, normalizedPoints);
	}

	public void clear() {
		points.clear();
	}

	@Override
	public String toString() {
		return String.format("Gesture '%s' with %d points", name, points.size());
	}
}
